﻿package net.wangit.jdbc.table;

import java.io.Serializable;

import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.JDBCException;
import net.wangit.jdbc.Type;
import net.wangit.jdbc.database.Database;
import net.wangit.jdbc.generator.GenerateRule;
import net.wangit.jdbc.generator.Generator;
import net.wangit.jdbc.sqltype.SqlType;


/**
 * 列
 * 
 * @author watson Feb 12, 2010
 */
@SuppressWarnings("serial")
public class Column implements Serializable {
	private Type type;
	private String name;
	private String label;
	private boolean nullable;
	private String defaultValue;
	private boolean quoted = false;
	private Generator generator;
	private int generateRule;
	private boolean autoByDB = false;

	public boolean isAutoByDB() {
		return this.autoByDB;
	}

	protected void setAutoByDB(boolean autoByDB) {
		this.autoByDB = autoByDB;
	}

	public Column(Type type) {
		this.type = type;
	}

	public Type getType() {
		return this.type;
	}

	public String getName() {
		return this.name;
	}

	protected void setName(String name) {
		this.name = name;
	}

	public String getQuotedName(Database d) {
		return ((this.quoted) ? d.openQuote() + this.name + d.closeQuote()
				: this.name);
	}

	public boolean isNullable() {
		return this.nullable;
	}

	protected void setNullable(boolean nullable) {
		this.nullable = nullable;
	}

	public SqlType getSqlType(Database database) {
		return getType().toSqlType(database);
	}

	public String getSqlTypeName(Database database) throws JDBCException {
		return getType().getSqlTypeName(database);
	}

	public String getDefaultValue() {
		return this.defaultValue;
	}

	protected void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}

	protected void setGenerator(Generator generator) {
		this.generator = generator;
	}

	protected void setGenerateRule(int generateRule) {
		this.generateRule = generateRule;
	}

	public String formatInput(String value) {
		return this.type.formatInput(value);
	}

	public boolean isEnabledByGenerator(ColumnRow row) {
		if (this.generator == null) {
			return false;
		}
		switch (this.generateRule) {
		case GenerateRule.ALL:
			return true;
		case GenerateRule.ADD:
			return row.isInsertRow();
		case GenerateRule.EDIT:
			return row.isUpdateRow();
		}
		return false;
	}

	public Generator getGenerator() {
		return this.generator;
	}

	public String getLabel() {
		return this.label;
	}

	public void setLabel(String label) {
		this.label = label;
	}
}